/*
 Xern Entity Relocation Network
 Copyright (C) 2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#ifndef XERN_METAVERSE_NODE_HPP
#define XERN_METAVERSE_NODE_HPP

#include <boost/thread.hpp>
#include "Xern/IMetaverseNode.hpp"
#include "Session.hpp"

namespace XernMetaverse
{
	using namespace Xern;

	class MessageTemplates;
	class MetaverseNode: public virtual IMetaverseNode
	{
	public:
		static const posix_time::time_duration NetworkThreadInterval;
		static const posix_time::time_duration PacketResendInterval;
		static const posix_time::time_duration KeepAliveInterval;
		static const posix_time::time_duration PacketDuplicationTolerance;
		static const int MaxResendCount;

		MetaverseNode(bool ipv6 = false);
		~MetaverseNode();

		virtual void Initialize();
		virtual void Shutdown();
		boost::shared_ptr<Message> CreateMessage(const std::string &name);

	protected:
		typedef std::multimap<udp::endpoint, boost::shared_ptr<Session> > Sessions;

		virtual bool OnReceiveMessage(boost::shared_ptr<Session> session, boost::shared_ptr<Message> message) = 0;

		// Messages.
		bool ReadTemplates();

		// Packet accounting.
		unsigned int GetPacketSequence();

		// Session management
		Sessions sessions;
		virtual void Session_Open(boost::shared_ptr<Session> session);
		void Session_Send(boost::shared_ptr<Session> session);
		void Session_SendAcks(boost::shared_ptr<Session> session);
		void Session_KeepAlive(boost::shared_ptr<Session> session);
		void Session_SendMessages(boost::shared_ptr<Session> session);
		void Session_ResendPackets(boost::shared_ptr<Session> session);
		void Session_CleanPackets(boost::shared_ptr<Session> session);
		void Session_ReceivePacket(boost::shared_ptr<Session> session, Packet &packet);

		// Send/Receive threads
		void SendThread();
		void ReceiveThread();

		// Network events.
		void OnPacketReceived(const boost::system::error_code &err, size_t size);
		void OnPacketReceivedV6(const boost::system::error_code &err, size_t size);
		void ProcessReceivedPacket(Packet &packet, udp::endpoint &endpoint);

		// Threading.
		boost::thread sendThread;
		boost::thread receiveThread;
		boost::mutex nodeMutex;

		// Sockets.
		boost::asio::io_service ioService;
		udp::socket socket;
		udp::socket socketV6;

		// Packet accounting.
		boost::mutex sequenceMutex;
		unsigned int sequenceNumber;
		unsigned int lastPingId;

		// Packet receiving.
		Packet receivedPacket, receivedPacketV6;
		udp::endpoint receiveEndpoint, receiveEndpointV6;

		// Node management.
		bool inited;
		bool shuttingDown;
		bool ipv6;

		// Messages.
		MessageTemplates templates;
		std::string messageTemplatesPath;

	};

}; // namespace XernMetaverse

#endif //XERN_METAVERSE_NODE_HPP
